# # from flask import Flask, request, jsonify
# # from flask_cors import CORS
# # import mysql.connector
# # from werkzeug.security import generate_password_hash, check_password_hash
# # import re
# #
# # # 创建Flask应用实例
# # app = Flask(__name__)
# # # 启用跨域资源共享(CORS)，允许前端从不同源访问API
# # CORS(app)
# #
# # # 数据库配置
# # db_config = {
# #     'host': 'localhost',
# #     'user': 'root',
# #     'password': '123456',
# #     'database': 'xu'
# # }
# #
# #
# # def get_db_connection():
# #     try:
# #         conn = mysql.connector.connect(**db_config)
# #         return conn
# #     except mysql.connector.Error as err:
# #         print(f"数据库连接错误: {err}")
# #         return None
# #
# #
# # def init_db():
# #     conn = get_db_connection()
# #     if conn is None:
# #         return False
# #
# #     try:
# #         cursor = conn.cursor()
# #
# #         # 创建用户表（包含手机号字段）
# #         cursor.execute('''
# #             CREATE TABLE IF NOT EXISTS users (
# #                 id INT AUTO_INCREMENT PRIMARY KEY,
# #                 username VARCHAR(50) UNIQUE NOT NULL,
# #                 phone VARCHAR(11) UNIQUE NOT NULL,
# #                 password VARCHAR(255) NOT NULL
# #             )
# #         ''')
# #
# #         # 检查是否有用户，如果没有则添加一个测试用户
# #         cursor.execute("SELECT COUNT(*) FROM users")
# #         count = cursor.fetchone()[0]
# #
# #         if count == 0:
# #             hashed_password = generate_password_hash('123456')
# #             cursor.execute(
# #                 "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
# #                 ('admin', '13800000000', hashed_password)
# #             )
# #
# #         conn.commit()
# #         return True
# #     except mysql.connector.Error as err:
# #         print(f"数据库初始化错误: {err}")
# #         return False
# #     finally:
# #         if conn.is_connected():
# #             conn.close()
# #
# #
# # def username_exists(username):
# #     conn = get_db_connection()
# #     if conn is None:
# #         return True
# #
# #     try:
# #         cursor = conn.cursor()
# #         cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
# #         return cursor.fetchone() is not None
# #     finally:
# #         if conn.is_connected():
# #             conn.close()
# #
# #
# # def phone_exists(phone):
# #     conn = get_db_connection()
# #     if conn is None:
# #         return True
# #
# #     try:
# #         cursor = conn.cursor()
# #         cursor.execute("SELECT id FROM users WHERE phone = %s", (phone,))
# #         return cursor.fetchone() is not None
# #     finally:
# #         if conn.is_connected():
# #             conn.close()
# #
# #
# # @app.route('/register', methods=['POST'])
# # def register():
# #     data = request.get_json()
# #     username = data.get('username')
# #     phone = data.get('phone')
# #     password = data.get('password')
# #
# #     # 验证必填字段
# #     if not username or not phone or not password:
# #         return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400
# #
# #     # 验证手机号格式
# #     if not re.match(r'^1[3-9]\d{9}$', phone):
# #         return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400
# #
# #     # 检查用户名是否已存在
# #     if username_exists(username):
# #         return jsonify({'success': False, 'message': '用户名已存在'}), 400
# #
# #     # 检查手机号是否已存在
# #     if phone_exists(phone):
# #         return jsonify({'success': False, 'message': '手机号已注册'}), 400
# #
# #     # 哈希密码
# #     hashed_password = generate_password_hash(password)
# #
# #     conn = get_db_connection()
# #     if conn is None:
# #         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
# #
# #     try:
# #         cursor = conn.cursor()
# #         cursor.execute(
# #             "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
# #             (username, phone, hashed_password)
# #         )
# #         conn.commit()
# #         return jsonify({'success': True, 'message': '注册成功'})
# #     except mysql.connector.Error as err:
# #         print(f"数据库错误: {err}")
# #         return jsonify({'success': False, 'message': '注册失败'}), 500
# #     finally:
# #         if conn.is_connected():
# #             conn.close()
# #
# #
# # @app.route('/login', methods=['POST'])
# # def login():
# #     data = request.get_json()
# #     username = data.get('username')
# #     password = data.get('password')
# #
# #     if not username or not password:
# #         return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
# #
# #     conn = get_db_connection()
# #     if conn is None:
# #         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
# #
# #     try:
# #         cursor = conn.cursor(dictionary=True)
# #         cursor.execute(
# #             "SELECT id, username, password FROM users WHERE username = %s",
# #             (username,)
# #         )
# #         user = cursor.fetchone()
# #
# #         if user and check_password_hash(user['password'], password):
# #             return jsonify({
# #                 'success': True,
# #                 'message': '登录成功'
# #             })
# #
# #         return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
# #     except mysql.connector.Error as err:
# #         print(f"数据库查询错误: {err}")
# #         return jsonify({'success': False, 'message': '数据库错误'}), 500
# #     finally:
# #         if conn.is_connected():
# #             conn.close()
# #
# #
# # if __name__ == '__main__':
# #     if init_db():
# #         print("数据库初始化成功")
# #         app.run(host='0.0.0.0', port=5001, debug=True)
# #     else:
# #         print("数据库初始化失败，请检查数据库配置")
#
# from flask import Flask, request, jsonify
# from flask_cors import CORS
# import mysql.connector
# from werkzeug.security import generate_password_hash, check_password_hash
# import re
#
# # 创建Flask应用实例
# app = Flask(__name__)
# # 启用跨域资源共享(CORS)，允许前端从不同源访问API
# CORS(app)
#
# # 数据库配置
# db_config = {
#     'host': 'localhost',
#     'user': 'root',
#     'password': '123456',
#     'database': 'xu'
# }
#
#
# def get_db_connection():
#     try:
#         conn = mysql.connector.connect(**db_config)
#         return conn
#     except mysql.connector.Error as err:
#         print(f"数据库连接错误: {err}")
#         return None
#
#
# def init_db():
#     conn = get_db_connection()
#     if conn is None:
#         return False
#
#     try:
#         cursor = conn.cursor()
#
#         # 创建用户表（包含手机号字段）
#         cursor.execute('''
#             CREATE TABLE IF NOT EXISTS users (
#                 id INT AUTO_INCREMENT PRIMARY KEY,
#                 username VARCHAR(50) UNIQUE NOT NULL,
#                 phone VARCHAR(11) UNIQUE NOT NULL,
#                 password VARCHAR(255) NOT NULL
#             )
#         ''')
#
#         # 检查是否有用户，如果没有则添加一个测试用户
#         cursor.execute("SELECT COUNT(*) FROM users")
#         count = cursor.fetchone()[0]
#
#         if count == 0:
#             hashed_password = generate_password_hash('123456')
#             cursor.execute(
#                 "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
#                 ('admin', '13800000000', hashed_password)
#             )
#
#         conn.commit()
#         return True
#     except mysql.connector.Error as err:
#         print(f"数据库初始化错误: {err}")
#         return False
#     finally:
#         if conn.is_connected():
#             conn.close()
#
#
# def username_exists(username):
#     conn = get_db_connection()
#     if conn is None:
#         return True
#
#     try:
#         cursor = conn.cursor()
#         cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
#         return cursor.fetchone() is not None
#     finally:
#         if conn.is_connected():
#             conn.close()
#
#
# def phone_exists(phone):
#     conn = get_db_connection()
#     if conn is None:
#         return True
#
#     try:
#         cursor = conn.cursor()
#         cursor.execute("SELECT id FROM users WHERE phone = %s", (phone,))
#         return cursor.fetchone() is not None
#     finally:
#         if conn.is_connected():
#             conn.close()
#
# # 添加以下路由到app.py中
#
# @app.route('/get-users', methods=['GET'])
# def get_users():
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor(dictionary=True)
#         cursor.execute("SELECT id, username, phone, password FROM users")
#         users = cursor.fetchall()
#         return jsonify({'success': True, 'users': users})
#     except mysql.connector.Error as err:
#         print(f"数据库查询错误: {err}")
#         return jsonify({'success': False, 'message': '获取用户数据失败'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
# @app.route('/add-user', methods=['POST'])
# def add_user():
#     data = request.get_json()
#     username = data.get('username')
#     phone = data.get('phone')
#     password = data.get('password')
#
#     if not username or not phone or not password:
#         return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400
#
#     if not re.match(r'^1[3-9]\d{9}$', phone):
#         return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400
#
#     if username_exists(username):
#         return jsonify({'success': False, 'message': '用户名已存在'}), 400
#
#     if phone_exists(phone):
#         return jsonify({'success': False, 'message': '手机号已注册'}), 400
#
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor()
#         cursor.execute(
#             "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
#             (username, phone, password)
#         )
#         conn.commit()
#         return jsonify({'success': True, 'message': '用户添加成功'})
#     except mysql.connector.Error as err:
#         print(f"数据库错误: {err}")
#         return jsonify({'success': False, 'message': '添加用户失败'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
# @app.route('/update-user', methods=['POST'])
# def update_user():
#     data = request.get_json()
#     user_id = data.get('id')
#     username = data.get('username')
#     phone = data.get('phone')
#     password = data.get('password')
#
#     if not user_id or not username or not phone or not password:
#         return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400
#
#     if not re.match(r'^1[3-9]\d{9}$', phone):
#         return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400
#
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor()
#         # 检查用户名是否被其他用户占用
#         cursor.execute(
#             "SELECT id FROM users WHERE username = %s AND id != %s",
#             (username, user_id)
#         )
#         if cursor.fetchone():
#             return jsonify({'success': False, 'message': '用户名已被其他用户使用'}), 400
#
#         # 检查手机号是否被其他用户占用
#         cursor.execute(
#             "SELECT id FROM users WHERE phone = %s AND id != %s",
#             (phone, user_id)
#         )
#         if cursor.fetchone():
#             return jsonify({'success': False, 'message': '手机号已被其他用户使用'}), 400
#
#         # 更新用户信息
#         cursor.execute(
#             "UPDATE users SET username = %s, phone = %s, password = %s WHERE id = %s",
#             (username, phone, password, user_id)
#         )
#         conn.commit()
#         return jsonify({'success': True, 'message': '用户信息更新成功'})
#     except mysql.connector.Error as err:
#         print(f"数据库错误: {err}")
#         return jsonify({'success': False, 'message': '更新用户信息失败'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
# @app.route('/delete-user', methods=['POST'])
# def delete_user():
#     data = request.get_json()
#     user_id = data.get('id')
#
#     if not user_id:
#         return jsonify({'success': False, 'message': '用户ID不能为空'}), 400
#
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor()
#         cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
#         conn.commit()
#         return jsonify({'success': True, 'message': '用户删除成功'})
#     except mysql.connector.Error as err:
#         print(f"数据库错误: {err}")
#         return jsonify({'success': False, 'message': '删除用户失败'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
#
# @app.route('/register', methods=['POST'])
# def register():
#     data = request.get_json()
#     username = data.get('username')
#     phone = data.get('phone')
#     password = data.get('password')
#
#     # 验证必填字段
#     if not username or not phone or not password:
#         return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400
#
#     # 验证手机号格式
#     if not re.match(r'^1[3-9]\d{9}$', phone):
#         return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400
#
#     # 检查用户名是否已存在
#     if username_exists(username):
#         return jsonify({'success': False, 'message': '用户名已存在'}), 400
#
#     # 检查手机号是否已存在
#     if phone_exists(phone):
#         return jsonify({'success': False, 'message': '手机号已注册'}), 400
#
#     # 哈希密码
#     hashed_password = generate_password_hash(password)
#
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor()
#         cursor.execute(
#             "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
#             (username, phone, hashed_password)
#         )
#         conn.commit()
#         return jsonify({'success': True, 'message': '注册成功'})
#     except mysql.connector.Error as err:
#         print(f"数据库错误: {err}")
#         return jsonify({'success': False, 'message': '注册失败'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
#
# @app.route('/login', methods=['POST'])
# def login():
#     data = request.get_json()
#     username = data.get('username')
#     password = data.get('password')
#
#     if not username or not password:
#         return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400
#
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor(dictionary=True)
#         cursor.execute(
#             "SELECT id, username, password FROM users WHERE username = %s",
#             (username,)
#         )
#         user = cursor.fetchone()
#
#         if user and check_password_hash(user['password'], password):
#             return jsonify({
#                 'success': True,
#                 'message': '登录成功'
#             })
#
#         return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
#     except mysql.connector.Error as err:
#         print(f"数据库查询错误: {err}")
#         return jsonify({'success': False, 'message': '数据库错误'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
#
# @app.route('/change-password', methods=['POST'])
# def change_password():
#     data = request.get_json()
#     username = data.get('username')
#     phone = data.get('phone')
#     new_password = data.get('new_password')
#
#     if not username or not phone or not new_password:
#         return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400
#
#     if not re.match(r'^1[3-9]\d{9}$', phone):
#         return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400
#
#     conn = get_db_connection()
#     if conn is None:
#         return jsonify({'success': False, 'message': '数据库连接失败'}), 500
#
#     try:
#         cursor = conn.cursor(dictionary=True)
#         # 验证用户名和手机号是否匹配
#         cursor.execute(
#             "SELECT id FROM users WHERE username = %s AND phone = %s",
#             (username, phone)
#         )
#         user = cursor.fetchone()
#
#         if not user:
#             return jsonify({'success': False, 'message': '用户名和手机号不匹配'}), 401
#
#         # 更新密码
#         hashed_password = generate_password_hash(new_password)
#         cursor.execute(
#             "UPDATE users SET password = %s WHERE username = %s",
#             (hashed_password, username)
#         )
#         conn.commit()
#         return jsonify({'success': True, 'message': '密码修改成功'})
#     except mysql.connector.Error as err:
#         print(f"数据库错误: {err}")
#         return jsonify({'success': False, 'message': '密码修改失败'}), 500
#     finally:
#         if conn.is_connected():
#             conn.close()
#
#
# if __name__ == '__main__':
#     if init_db():
#         print("数据库初始化成功")
#         app.run(host='0.0.0.0', port=5001, debug=True)
#     else:
#         print("数据库初始化失败，请检查数据库配置")

from flask import Flask, request, jsonify
from flask_cors import CORS
import mysql.connector
import re

# 创建Flask应用实例
app = Flask(__name__)
# 启用跨域资源共享(CORS)，允许前端从不同源访问API
CORS(app)

# 数据库配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'password': '123456',
    'database': 'kafkawork'
}

def get_db_connection():
    try:
        conn = mysql.connector.connect(**db_config)
        return conn
    except mysql.connector.Error as err:
        print(f"数据库连接错误: {err}")
        return None

def init_db():
    conn = get_db_connection()
    if conn is None:
        return False

    try:
        cursor = conn.cursor()

        # 创建用户表（包含手机号字段）
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INT AUTO_INCREMENT PRIMARY KEY,
                username VARCHAR(50) UNIQUE NOT NULL,
                phone VARCHAR(11) UNIQUE NOT NULL,
                password VARCHAR(255) NOT NULL
            )
        ''')

        # 检查是否有用户，如果没有则添加一个测试用户
        cursor.execute("SELECT COUNT(*) FROM users")
        count = cursor.fetchone()[0]

        if count == 0:
            cursor.execute(
                "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
                ('admin', '13800000000', '123456')
            )

        conn.commit()
        return True
    except mysql.connector.Error as err:
        print(f"数据库初始化错误: {err}")
        return False
    finally:
        if conn.is_connected():
            conn.close()

def username_exists(username):
    conn = get_db_connection()
    if conn is None:
        return True

    try:
        cursor = conn.cursor()
        cursor.execute("SELECT id FROM users WHERE username = %s", (username,))
        return cursor.fetchone() is not None
    finally:
        if conn.is_connected():
            conn.close()

def phone_exists(phone):
    conn = get_db_connection()
    if conn is None:
        return True

    try:
        cursor = conn.cursor()
        cursor.execute("SELECT id FROM users WHERE phone = %s", (phone,))
        return cursor.fetchone() is not None
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/get-users', methods=['GET'])
def get_users():
    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT id, username, phone, password FROM users")
        users = cursor.fetchall()
        return jsonify({'success': True, 'users': users})
    except mysql.connector.Error as err:
        print(f"数据库查询错误: {err}")
        return jsonify({'success': False, 'message': '获取用户数据失败'}), 500
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/add-user', methods=['POST'])
def add_user():
    data = request.get_json()
    username = data.get('username')
    phone = data.get('phone')
    password = data.get('password')

    if not username or not phone or not password:
        return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400

    if not re.match(r'^1[3-9]\d{9}$', phone):
        return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400

    if username_exists(username):
        return jsonify({'success': False, 'message': '用户名已存在'}), 400

    if phone_exists(phone):
        return jsonify({'success': False, 'message': '手机号已注册'}), 400

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
            (username, phone, password)
        )
        conn.commit()
        return jsonify({'success': True, 'message': '用户添加成功'})
    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        return jsonify({'success': False, 'message': '添加用户失败'}), 500
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/update-user', methods=['POST'])
def update_user():
    data = request.get_json()
    user_id = data.get('id')
    username = data.get('username')
    phone = data.get('phone')
    password = data.get('password')

    if not user_id or not username or not phone or not password:
        return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400

    if not re.match(r'^1[3-9]\d{9}$', phone):
        return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor()
        # 检查用户名是否被其他用户占用
        cursor.execute(
            "SELECT id FROM users WHERE username = %s AND id != %s",
            (username, user_id)
        )
        if cursor.fetchone():
            return jsonify({'success': False, 'message': '用户名已被其他用户使用'}), 400

        # 检查手机号是否被其他用户占用
        cursor.execute(
            "SELECT id FROM users WHERE phone = %s AND id != %s",
            (phone, user_id)
        )
        if cursor.fetchone():
            return jsonify({'success': False, 'message': '手机号已被其他用户使用'}), 400

        # 更新用户信息
        cursor.execute(
            "UPDATE users SET username = %s, phone = %s, password = %s WHERE id = %s",
            (username, phone, password, user_id)
        )
        conn.commit()
        return jsonify({'success': True, 'message': '用户信息更新成功'})
    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        return jsonify({'success': False, 'message': '更新用户信息失败'}), 500
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/delete-user', methods=['POST'])
def delete_user():
    data = request.get_json()
    user_id = data.get('id')

    if not user_id:
        return jsonify({'success': False, 'message': '用户ID不能为空'}), 400

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor()
        cursor.execute("DELETE FROM users WHERE id = %s", (user_id,))
        conn.commit()
        return jsonify({'success': True, 'message': '用户删除成功'})
    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        return jsonify({'success': False, 'message': '删除用户失败'}), 500
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    username = data.get('username')
    phone = data.get('phone')
    password = data.get('password')

    if not username or not phone or not password:
        return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400

    if not re.match(r'^1[3-9]\d{9}$', phone):
        return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400

    if username_exists(username):
        return jsonify({'success': False, 'message': '用户名已存在'}), 400

    if phone_exists(phone):
        return jsonify({'success': False, 'message': '手机号已注册'}), 400

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor()
        cursor.execute(
            "INSERT INTO users (username, phone, password) VALUES (%s, %s, %s)",
            (username, phone, password)
        )
        conn.commit()
        return jsonify({'success': True, 'message': '注册成功'})
    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        return jsonify({'success': False, 'message': '注册失败'}), 500
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    username = data.get('username')
    password = data.get('password')

    if not username or not password:
        return jsonify({'success': False, 'message': '用户名和密码不能为空'}), 400

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor(dictionary=True)
        cursor.execute(
            "SELECT id, username, password FROM users WHERE username = %s",
            (username,)
        )
        user = cursor.fetchone()

        if user and user['password'] == password:
            return jsonify({
                'success': True,
                'message': '登录成功'
            })

        return jsonify({'success': False, 'message': '用户名或密码错误'}), 401
    except mysql.connector.Error as err:
        print(f"数据库查询错误: {err}")
        return jsonify({'success': False, 'message': '数据库错误'}), 500
    finally:
        if conn.is_connected():
            conn.close()

@app.route('/change-password', methods=['POST'])
def change_password():
    data = request.get_json()
    username = data.get('username')
    phone = data.get('phone')
    new_password = data.get('new_password')

    if not username or not phone or not new_password:
        return jsonify({'success': False, 'message': '所有字段都必须填写'}), 400

    if not re.match(r'^1[3-9]\d{9}$', phone):
        return jsonify({'success': False, 'message': '请输入有效的手机号码'}), 400

    conn = get_db_connection()
    if conn is None:
        return jsonify({'success': False, 'message': '数据库连接失败'}), 500

    try:
        cursor = conn.cursor(dictionary=True)
        # 验证用户名和手机号是否匹配
        cursor.execute(
            "SELECT id FROM users WHERE username = %s AND phone = %s",
            (username, phone)
        )
        user = cursor.fetchone()

        if not user:
            return jsonify({'success': False, 'message': '用户名和手机号不匹配'}), 401

        # 更新密码
        cursor.execute(
            "UPDATE users SET password = %s WHERE username = %s",
            (new_password, username)
        )
        conn.commit()
        return jsonify({'success': True, 'message': '密码修改成功'})
    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        return jsonify({'success': False, 'message': '密码修改失败'}), 500
    finally:
        if conn.is_connected():
            conn.close()

if __name__ == '__main__':
    if init_db():
        print("数据库初始化成功")
        app.run(host='0.0.0.0', port=5001, debug=True)
    else:
        print("数据库初始化失败，请检查数据库配置")